package com.jiuyin.dianjing.ui.fragment.base;

import android.os.Bundle;
import android.view.View;

/**
 * Description:
 * 懒加载的BaseFragment
 * File: BaseLazyFragment.java
 * Create: 2019/04/29 15:13
 *
 * @Author: Administrator
 */
public abstract class BaseLazyFragment extends BaseFragment {
    // 判断界面用户是否可见
    private boolean mIsVisibleToUser;
    // 判断View是否创建
    private boolean mIsViewInitialized;
    private boolean mIsLazyLoaded;

    /**
     * fragment是否在当前界面
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.mIsVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    /**
     * 懒加载
     */
    public abstract void fetchData();

    /**
     * 判断懒加载条件
     */
    private void prepareFetchData() {
        if (mIsVisibleToUser && mIsViewInitialized && !mIsLazyLoaded) {
            mIsLazyLoaded = true;
            initData();
            initView();
            fetchData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsViewInitialized = false;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mIsViewInitialized = true;
        prepareFetchData();
    }
}
